package com.github.pagehelper.parser;

import com.github.pagehelper.filter.Filter;
import com.github.pagehelper.filter.entity.AbstractCondition;
import com.github.pagehelper.filter.entity.ArrayCondition;
import com.github.pagehelper.filter.entity.TextCondition;

import java.util.Map;

public class FilterSqlParser {

    public String getSmartCountSql(String sql, Map<String, Object> filterParams) {
        if (filterParams.size() > 0) {
            Filter filter =  new Filter(filterParams);

            StringBuilder sbQuery = new StringBuilder();

            for (int i = 0; i<filter.getConditions().size(); i++) {
                AbstractCondition c = filter.getConditions().get(i);
                if (c instanceof ArrayCondition) {
                    StringBuilder in = new StringBuilder();
                    in.append(" and ").append(c.getName()).append(" in (");
                    Object[] v = ((ArrayCondition) c).getValue();
                    for(Object o : v){
                        in.append("'").append(o.toString()).append("',");
                    }
                    if (v.length > 0) {
                        in.delete(in.length()-1, in.length());
                        in.append(") ");
                        sbQuery.append(in);
                    }
                } else if (c instanceof TextCondition) {
                    Object v = ((TextCondition) c).getValue();
                    sbQuery.append(" and ").append(c.getName()).append(" like '%").append(v.toString()).append("%' ");
                }
            }

            String sqlFinal = "select _t.* from ( " + sql + " ) _t where " + sbQuery.toString().substring(4);

            return sqlFinal;
        } else {
            return "";
        }
    }
}
